package com.weight.common.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import com.weight.WeightmgApplication;
import com.weight.common.enums.ResultEnum;
import com.weight.netty.NettyBooter;
import com.weight.system.weight.PO.WeightInfo;
import com.weight.system.weight.VO.WeightInfoVO;
import com.weight.system.weight.service.WeightInfoService;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
 
public class ChannelUtil {
	//连接串 Map
	public static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<String, Channel>();
	// 连接串 数组
    public static final ChannelGroup  userChannelClients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    //收发 指令 临时
    public static final Map<String, Map<String, String>> userChannelTemp = new ConcurrentHashMap<String, Map<String, String>>();
    
    //注册码 对照 连接串 临时
    public static final Map<String, String> userCodeMapTemp = new ConcurrentHashMap<String, String>();
    // 连接串 对照 注册码 临时
    public static final Map<String, String> userAddressMapTemp = new ConcurrentHashMap<String, String>();
    
    //用户登录后保存用户channel
    public static void saveChannel(String address, Channel channel){
//    	System.out.println(address);
    	userChannelClients.add(channel);  
        userChannelMap.put(address, channel);
        
        userAddressMapTemp.put(address, "msgcode");
        Map<String, String> map = new ConcurrentHashMap<String, String>();
        map.put("msgcode","msgcode");//注册码        
        userChannelTemp.put(address, map);
        
    }
    public static Map<String, String> getTempMsg(Channel channel){
    	Map<String, String> map  = new ConcurrentHashMap<String, String>();
    	if(null == channel) {
    		return map;
    	} 
    	String address = channel.remoteAddress().toString();
    	if(StringUtils.contains(address, ":")) {
    		address = address.substring(address.lastIndexOf(":")+1);
    	}
    	 map = userChannelTemp.get(address); 
    	 return map;
    }
    /**
     * 	指令返回信息
     * @param channel
     * @param Msg
     * @return
     */
    public static String saveTempMsg(Channel channel,String Msg){
    	if(null == channel) {
    		return "";
    	}
    	
    	String address = channel.remoteAddress().toString();
    	if(StringUtils.contains(address, ":")) {
    		address = address.substring(address.lastIndexOf(":")+1);
    	}
    	//取注册码
    	String msgcode =  userAddressMapTemp.get(address);
    	//连接后第一条指令为注册码
     
    	//首次连接 注册码为 msgcode
    	if(StringUtils.equals("msgcode", msgcode)) {
//    		userCodeMapTemp.put(Msg, address);
    		System.out.println(""+ Msg+" ====="+address);
//    		clearTempMsg( msgcode);
    		userCodeMapTemp.put(Msg, address);
            userAddressMapTemp.put(address, Msg);
            userChannelTemp.get(address).put("msgcode",Msg);
            
            System.out.println("第一次注册码：" + Msg);
            return "msgcode";
    	}
//    	clearTempMsg( msgcode);
//		userCodeMapTemp.put(msgcode, address);
//      userAddressMapTemp.put(address, msgcode);
//      userChannelTemp.get(address).put("msgcode",msgcode);
        
    	return saveTempMsg(address, Msg);
    }
    /**
     * 	释放重复连接
     * @param msgcode
     */
    public static void clearTempMsg(String msgcode){
    	//注册码 连接 是否已存在
		String oldAddress = userCodeMapTemp.get(msgcode);
		
		//已存在
		if(StringUtils.isBlank(oldAddress)) {
			return;
		}
		
		Channel oldChannel = userChannelMap.get(oldAddress);
		if(null == oldChannel) {
			return;
		} 
		// 清除连接
		ChannelUtil.removeChannel(oldChannel);
		 
    }
    
    public static String saveTempMsg(String address,String Msg){
    	
//    	System.out.println(address);
    	//取临时 数据
    	Map<String, String> map = userChannelTemp.get(address);
    	System.out.println("解析指令:");
    	System.out.println(map);
    	//解析指令
    	Map<String, String> mapMsg = operMsg(Msg);   
//    	
//    	System.out.println(mapMsg);
//    	System.out.println(mapMsg.get("command"));
//    	System.out.println(mapMsg.get("message"));
    	if(StringUtils.isBlank(mapMsg.get("command")) || StringUtils.isBlank(mapMsg.get("message"))) {
    		return "";
    	}
    	
    	map.put(mapMsg.get("command"), mapMsg.get("message")); 
    	return mapMsg.get("command");
    }
    /**
     * 	指令解析
     * @param Msg
     * 	map.put("lenStr", lenStr);//指令长度
		map.put("command", command);//指令
		map.put("message", message);//指令内容
     * @return
     */
    public static Map<String, String> operMsg(String Msg){
    	System.out.println("operMsg111111111");
    	System.out.println(Msg);
    	Map<String, String> map =  new ConcurrentHashMap<String, String>();
    	if(StringUtils.isBlank(Msg) || Msg .length() < 10) {
    		return map;
    	}
    	if(StringUtils.startsWith(Msg, "2B47505349")) {
    		Msg =  CommonUtils.hexStringToString(Msg); 
    		map.put("lenStr", "" + Msg.length());//指令长度
    		map.put("command", "GPSINFO");//指令
    		map.put("message", Msg);//指令内容
    		 
    		return map;		
    	}
    	
    	//A5 5A 06 01 00 00 12 34 56 
	    Msg = Msg.replaceAll(" ", "").substring(4);//A5 5A 
//	    System.out.println(Msg);
	    String lenStr = Msg.substring(0,2);//06
//	    System.out.println(lenStr);
	    String command = Msg.substring(2,6);//0100
//		System.out.println(msg);
		String message = Msg.substring(6);//00123456
//		System.out.println(message);		
		//指令解析格式
		String commandType = NettyBooter.commandMap.get(command);
		
		
		//校验 数据库 指令
//		if(null == commandType) {
//			return map;
//		}
		
		// 接收指令转换
		message =CommonUtils.operSaveMSG(commandType, command, message);		
		map.put("lenStr", lenStr);//指令长度
		map.put("command", command);//指令
		map.put("message", message);//指令内容
		 
		return map;		
    }    
    
    /**
     * 	用户上线  存储连接
     * @param channel
     */
    public static void saveChannel(Channel channel){
    	if(null == channel) {
    		return;
    	}
    	String address = channel.remoteAddress().toString();
    	if(StringUtils.contains(address, ":")) {
    		address = address.substring(address.lastIndexOf(":")+1);
    	}
    	saveChannel(address, channel);
    }
    /**
     * 	用户下线  释放连接
     * @param channel
     */
    public static void removeChannel(Channel channel){
    	if(null == channel) {
    		return;
    	}
    	String address = channel.remoteAddress().toString();
    	if(StringUtils.contains(address, ":")) {
    		address.substring(address.lastIndexOf(":")+1);
    	} 
    	
    	//删除 连接
    	userChannelClients.remove(channel);  
    	//删除 连接
        userChannelMap.remove(address); 
//        
//        Map<String, String> map = userChannelTemp.get(address);
//        String msgcode = map.get("msgcode");
//        userCodeMapTemp.remove(msgcode);
        
        //删除 连接 临时数据
        userChannelTemp.remove(address);
        
    }
    
    /**
     * 	连接串address 查找channel
     * @param address
     * @return
     */
    public static Channel getChannel(String address){
    	Channel cx = userChannelMap.get(address);
        return cx;
    } 
}
